package com.weixing.mall.provider.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.google.common.collect.Lists;
import com.weixing.mall.base.enums.BussessSnPrefixEnum;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.pay.enums.PayChannelEnum;
import com.weixing.mall.provider.api.model.CalcProfitPo;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.domain.OrderExpress;
import com.weixing.mall.util.CommUtil;
import jodd.util.StringUtil;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单工具类
 *
 * @author  siashan
 * @date  2019/12/9 9:18
 * @since  1.0
 **/
public class OrderUtil {

    /**
     * 生成交易流水号
     *
     * @apiNote 格式：  XXXXXXXXXXXX      +    X        +   XXXXX
     *          注释： 时间（年月日时分秒）  +    支付渠道  +    流水号
     *          例子：  20191209112948     +       2       +   8934
     * @param payChannel     支付渠道
     * @param transNo   流水号
     * @param now  当前日期
     * @return 交易流水号
     */
    public static String genTradeNo(PayChannelEnum payChannel, long transNo, Date now) {
        StringBuilder sb = new StringBuilder();

        String format = DateUtil.format(now, "yyyyMMddHHmmss");
        // 时间戳
        sb.append(format);
        // 支付渠道
        sb.append(payChannel.getCode());
        // 流水号
        sb.append(parseTransNo(transNo, 5));
        return sb.toString();
    }


    /**
     * 格式化流水号
     *
     * @apiNote 位数不够补0
     * @param tNo  流水号
     * @param len  位数
     * @return  流水号
     */
    private static String parseTransNo(Long tNo, int len) {
        String transNo = String.valueOf(tNo);
        return transNo.length() < len ? String.format("%05d", tNo) : transNo;
    }



    /**
     * 生成子订单订单编号
     *
     * @param prefix  前缀   正价：ZJ  秒杀：MS  代理  DL
     * @param fmtDate  格式化的日期   eg:20200515
     * @param seq   自增序列号
     * @return 订单编号
     */
    public static String genSubOrderSn(String prefix, String fmtDate, Long seq) {
        return prefix + fmtDate + parseTransNo(seq, 5) + RandomUtil.randomNumbers(3);
    }


    /**
     * 封装订单收货地址
     *
     * @param express   订单快递
     * @date  2020/3/10 15:30
     * @return 收货地址
     */
    public static String wrapperShipAddr(OrderExpress express) {
        StringBuilder sb = new StringBuilder();
        sb.append(express.getProvince()).append(express.getCity())
                .append(express.getRegion()).append(express.getTown())
                .append(express.getAddrDetail());
        return sb.toString();
    }


    /**
     * 处理订单代理认领结构
     *
     * @param order   订单
     * @date  2020/3/17 9:58
     */
    public static void doOrderAgentClaim(Order order) {

        String agentTreePath = order.getAgentCliamLine();
        if (StringUtil.isEmpty(agentTreePath)) {
            return;
        }
        List<CalcProfitPo> calcProfitPos = parseTreePath(agentTreePath);
        order.setDistributorId(0L);
        order.setLevel1st(0L);
        order.setLevel2nd(0L);
        order.setLevel3rd(0L);
        order.setLevel4th(0L);
        for (CalcProfitPo po : calcProfitPos) {
            long agentId = po.getAgentId();
            AgentLevelEnum level = EnumUtil.getIEnum(AgentLevelEnum.class, po.getAgentLevel());
            // 初始化原有等级
            switch (level) {
                case DEALER:
                    order.setDistributorId(agentId);
                    break;
                case LEVEL_1:
                    order.setLevel1st(agentId);
                    break;
                case LEVEL_2:
                    order.setLevel2nd(agentId);
                    break;
                case LEVEL_3:
                    order.setLevel3rd(agentId);
                    break;
                case LEVEL_4:
                    order.setLevel4th(agentId);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 清理订单代理认领结构
     *
     * @param order 订单
     */
    public static void clearOrderAgentClaim(Order order) {
        order.setDistributorId(0L);
        order.setLevel1st(0L);
        order.setLevel2nd(0L);
        order.setLevel3rd(0L);
        order.setLevel4th(0L);
    }


    /**
     * 解析订单认领结构树
     * @param treePath  认领结构树
     * @return  结构树
     */
    public static List<CalcProfitPo> parseTreePath(String treePath) {
        String[] agentCliamDetail = treePath.split("\\|");
        List<CalcProfitPo> calcProfitPos = Lists.newArrayList();
        CalcProfitPo calcProfitPo = null;
        for (String agentDetail : agentCliamDetail) {
            String[] detail = agentDetail.split(":");
            int agentLevel = Integer.parseInt(detail[0]);
            int agentType = Integer.parseInt(detail[1]);
            BigDecimal discount = new BigDecimal(detail[3]);
            long agentId = Long.parseLong(detail[2]);
            calcProfitPo = new CalcProfitPo();
            calcProfitPo.setAgentId(agentId);
            calcProfitPo.setAgentLevel(agentLevel);
            calcProfitPo.setAgentType(agentType);
            calcProfitPo.setDiscount(discount);
            calcProfitPos.add(calcProfitPo);
        }
        return calcProfitPos;
    }


    public static CalcProfitPo getCalcProfitPo(Long agentId, List<CalcProfitPo> calcProfitPos) {
        CalcProfitPo po = null;
        int lenth = calcProfitPos.size();
        for (int i = 0; i < lenth; i++) {
            CalcProfitPo calcProfitPo = calcProfitPos.get(i);
            long aId = calcProfitPo.getAgentId();
            // 计算出当前登录的代理商
            if (agentId.longValue() == aId) {
                po = calcProfitPo;
                po.setIndex(i);
                break;
            }
        }
        return po;
    }


    public static void main(String[] args) {

//        AliTradeTypeEnum pc = Enum.valueOf(AliTradeTypeEnum.class,"PC");
//        System.out.println(pc.getScene());
//
//
//
//        System.out.println("20191209200623134".charAt(14));
//
//
//        Object iEnum = com.weixing.mall.base.utils.EnumUtil.getIEnum(PayChannelEnum.class, "ali");
//        System.out.println(iEnum);

//        String str = "20191209112948_11111";
//        System.out.println(str.substring(0, 14));

        // 订单编号
//        String zj = genSubOrderSn("ZJ", "20200515", 123456L);
//        System.out.println(zj);
        //订单识别码
//        long id = 100;
//        String encode = OrderCodeUtil.encode((int) id);
//        System.out.println(encode);


        Order order = new Order();
        order.setAgentCliamLine("2:1:86:0.58|1:1:85:0.48");
        doOrderAgentClaim(order);

    }

}
